package flex.cc.uac.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import flex.cc.PublicUtil;
import flex.cc.base.dto.LoginAuthDto;
import flex.cc.core.annotation.OperationLogDto;
import flex.cc.uac.dao.UacLogDao;
import flex.cc.uac.dto.log.UacLogMainDto;
import flex.cc.uac.entity.UacActionEntity;
import flex.cc.uac.entity.UacLogEntity;
import flex.cc.uac.service.UacActionService;
import flex.cc.uac.service.UacLogService;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;


@Service("uacLogService")
@Transactional(rollbackFor = Exception.class)
public class UacLogServiceImpl extends ServiceImpl<UacLogDao, UacLogEntity> implements UacLogService {

    @Resource
    private UacLogDao uacLogDao;


    @Resource
    private UacActionService uacActionService;

    @Override
    public boolean saveLog(UacLogEntity uacLogEntity, LoginAuthDto loginAuthDto) {
        // 根据uri 查询url对应的权限
        UacActionEntity uacActionEntity = uacActionService.matchesByUrl(uacLogEntity.getRequestUrl());
        if (uacActionEntity != null) {
            uacLogEntity.setActionId(uacActionEntity.getId());
            uacLogEntity.setActionCode(uacActionEntity.getActionCode());
            uacLogEntity.setActionName(uacActionEntity.getActionName());
        }
        uacLogEntity.setUpdateInfo(loginAuthDto);
        return  this.save(uacLogEntity);
    }

    @Override
    public Boolean saveOperationLog(OperationLogDto operationLogDto) {
        // 根据uri 查询url对应的权限
        UacActionEntity uacAction = uacActionService.matchesByUrl(operationLogDto.getRequestUrl());
        if (uacAction != null) {
            operationLogDto.setActionCode(uacAction.getActionCode());
            operationLogDto.setActionName(uacAction.getActionName());
            operationLogDto.setActionId(uacAction.getId());
        }
        ModelMapper modelMapper = new ModelMapper();
        UacLogEntity uacLog = modelMapper.map(operationLogDto, UacLogEntity.class);
        return this.save(uacLog);
    }


    @Override
    public IPage<UacLogEntity> queryLogListWithPage(UacLogMainDto uacLogMainDto) {
        List<Long> menuIdList = uacLogMainDto.getMenuIdList();
        Long actionId = null;
        if (PublicUtil.isNotEmpty(menuIdList)) {
            actionId = menuIdList.get(menuIdList.size() - 1);
        }
        uacLogMainDto.setMenuId(actionId);
        IPage<UacLogEntity> page = new Page<>(uacLogMainDto.getPageNum(),uacLogMainDto.getPageSize());
        return uacLogDao.queryLogListWithPage(page,uacLogMainDto);
    }

}